using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Table;

namespace AzureDiagnostics2Excel
{
    class TableRepository
    {
        public IEnumerable<PerformanceCounterEntity> GetPerformanceCountersInTimeSpan(string connectionString, DateTime from, DateTime to)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            CloudTable performanceCounterTable = tableClient.GetTableReference("WADPerformanceCountersTable");

            TableQuery<PerformanceCounterEntity> rangeQuery = new TableQuery<PerformanceCounterEntity>().Where(TableQuery.CombineFilters(
                TableQuery<PerformanceCounterEntity>.GenerateFilterCondition("PartitionKey", QueryComparisons.GreaterThanOrEqual, "0" + from.Ticks.ToString()),
                TableOperators.And,
                TableQuery<PerformanceCounterEntity>.CombineFilters(
                    TableQuery<PerformanceCounterEntity>.GenerateFilterCondition("PartitionKey", QueryComparisons.LessThanOrEqual, "0" + to.Ticks.ToString()),
                    TableOperators.And,
                    TableQuery.CombineFilters(
                        TableQuery<PerformanceCounterEntity>.GenerateFilterConditionForLong("EventTickCount", QueryComparisons.GreaterThanOrEqual, from.Ticks),
                        TableOperators.And,
                        TableQuery<PerformanceCounterEntity>.GenerateFilterConditionForLong("EventTickCount", QueryComparisons.LessThanOrEqual, to.Ticks)
                        )
                    )
                ));

            var counters = performanceCounterTable.ExecuteQuery(rangeQuery);

            return counters;
        }
    }

}
